myapp.views.NearMe = Ext.extend(Ext.Panel, {
		initComponent : function () {
			console.log('NearMe inited');
			//myapp.geoLocation.updateLocation();
/*			var geo = new Ext.util.GeoLocation({
			    autoUpdate: false,
			    listeners: {
			        locationupdate: function (geo) {
			            alert('New latitude: ' + geo.latitude);
			        },
			        locationerror: function (   geo,
			                                    bTimeout, 
			                                    bPermissionDenied, 
			                                    bLocationUnavailable, 
			                                    message) {
			            if(bTimeout){
			                alert('Timeout occurred.');
			            }
			            else{
			                alert('Error occurred.');
			            }
			        }
			    }
			});
			geo.updateLocation();*/
			/* can overload initComponent method here, but be sure to run superclass function */
			myapp.views.NearMe.superclass.initComponent.apply(this, arguments);
		},
		dockedItems : [{
				record : {},
				xtype : 'toolbar',
				title : 'Location',
				items : [{
						id : 'back_to_museum',
						text : 'Back',
						ui : 'back',
						listeners : {
							'tap' : function () {
								Ext.dispatch({
									controller : myapp.controllers.index,
									action : 'index',
									animation : {
										type : 'slide',
										direction : 'right'
									}
								});
							}
						}
					}
				]
			}
		],
		activate : function (sender) {
			console.log(' nearMe activated!');
			// sender gets reset to top of page. Only really useful from museum detail page
			sender.body.scrollTo("top", 0, true); 
		},
		updateWithRecord : function (record) {
			console.log('in updateWithRecord!');
			myapp.views.MuseumDetailMap.record = record;
			
			if (myapp.views.MuseumDetailMap.record.data.latitude == '' ||
				myapp.views.MuseumDetailMap.record.data.longitude == '') {
				console.log('record has no geometry.');
				myapp.views.museumDetailMap.geoCodeAddress(record);
			} else {
				console.log('Record has geometry.');
				//myapp.views.museumDetailMap.setupMarker(record);
				//myapp.views.museumDetailMap.centerAndZoomMap(record);
			}
		},
		geoCodeAddress : function (address) {
			console.log('In geoCodeAddress');
			var g = myapp.views.museumDetailMap.geocoder;
			g.geocode({
				'address' : address
			}, function (results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					//alert('Status OK!');
					map.map.setCenter(results[0].geometry.location);
					var marker = new google.maps.Marker({
							map : map.map,
							position : results[0].geometry.location,
							animation : google.maps.Animation.DROP,
							title : myapp.views.museumDetailMap.record.data.name
						});
					var infowindow = new google.maps.InfoWindow({
							//content: contentString
							content : myapp.views.museumDetailMap.getContentString()
						});
					google.maps.event.addListener(marker, 'click', function () {
						infowindow.open(map, marker);
					});
				} else {
					console.log("Geocode was not successful for the following reason: " + status);
				}
			});
		},
		getContentString : function (museum) {
			var theReturn = '<div class="mapMarkerInfowindow">' +
				'<p>' + museum.museumName + '</p>' +
				'</div>';
			return theReturn;
		},
		centerAndZoomMap : function (record) {
			console.log('centering and zooming');
			//var location = new google.maps.LatLng(-123.401184, 48.461084);
			var location = new google.maps.LatLng(record.data.latitude, record.data.longitude);
			// TODO below latlngbounds is null so erroring. Because map object not created fast enough?
			// was working when we were geocoding everything
			//map2.map.setCenter(myapp.models.markers.latlngbounds.getCenter(), map2.map.fitBounds(myapp.models.markers.latlngbounds));
			//myapp.views.museumDetailMap.map.mapOptions.center = location;
			myapp.views.museumDetailMap.map
			//myapp.views.museumDetailMap.map.setCenter(location);
			myapp.views.museumDetailMap.setupMarker(record);
		},
		addMap : function () {
			var pos = new google.maps.LatLng(48.461084,-123.401184); // default to Victoria
			if (myapp.geoLocation.latitude != null && myapp.geoLocation.longitude != null)
				pos = new google.maps.LatLng(myapp.geoLocation.latitude,myapp.geoLocation.longitude);

			var isRefreshRequired = false;
			if (this.getComponent(0).getXTypes() === 'box/map') {
				console.log('XTypes === box/map');
				this.remove(this.getComponent(0));
				isRefreshRequired = true;
			}
			
			var map = new Ext.Map({
					fullscreen : true,
					title : 'Museums Near Me',
					plugins: [new Ext.ux.touch.MapLoader({ // see: /lib/Ext.ux.touch.MapLoader.js
						units: 'miles',
						bufferType: 'ratio',
						buffer: 0.25, // calculate 25% of the visible radius,
						loadInterval: 300 // do a load every 300 ms during panning
					})],
					//markerDesc: desc,
					centered: true,
					markerPos : pos,
					mapOptions : {
						zoom : 12, //12
						center : pos,
						mapTypeControl : true,
						panControl : false,
						scrollwheel : false,
						streetViewControl : false
					},
					listeners : {
						delay : 500,
						afterrender : function () {
							console.log('afterrender');
							// at this point, this.map was undefined. Why? should have reference to map
							// took out "scope", and now this appears to be working
							//myapp.views.nearMe.setupMarkers(museums, this.map);
						},
						mapload : this.onMapLoad, // new event created by MapLoader plugin
					}
				});
			this.add(map);
			console.log('adding map');
			if (isRefreshRequired)
				this.doLayout();
		},
		// =============================
		// event fires when user updates map bounds (pans, etc)
		// =============================
		onMapLoad: function(centre, bounds, boundingRadius, bufferRadius, zoom){
	    	var museumsWithinBounds = myapp.stores.museums.markersWithinBounds(bounds);
	    	var museumsToPlot = [];
	    	
	    	Ext.each(museumsWithinBounds, function (museum){
	    		if(!myapp.views.nearMe.plottedMuseums.contains(museum)){
	    			museumsToPlot.push(museum);
	    			myapp.views.nearMe.plottedMuseums.push(museum)
	    		}
	    	});
	    	
	    	myapp.views.nearMe.setupMarkers(museumsToPlot, this.map);

	    	console.log('mapLoad with:');
			console.log('centre: ' + Ext.encode(centre));
			console.log('bounds: ' + bounds);
			console.log('boundingRadius: ' + boundingRadius);
			console.log('boundingRadius: ' + boundingRadius);
			console.log('zoom: ' + zoom);
	    },
		setupMarkers : function (museumsToPlot, theMap) {
			console.log('In setupMarkers');
			var iterator = 0; // to go back through museums one at a time and build markers after setTimeout
			for (var i = 0; i < museumsToPlot.length; i++) {
				setTimeout(function() {
					var record = museumsToPlot[iterator];
					iterator++;
					var location = new google.maps.LatLng(record.latitude, record.longitude);
					if (record.latitude && record.longitude) // only plot museums with geography
					{
						var marker = new google.maps.Marker({
								map : theMap,
								position : location,
								animation : google.maps.Animation.DROP,
								title : record.museumName
							});
						var infowindow = new google.maps.InfoWindow({
								content : record.museumName,
								maxWidth: 200
								//content : myapp.views.museumDetailMap.getContentString(record)
							});
						google.maps.event.addListener(marker, 'click', function () {
							infowindow.open(theMap, marker);
						});
					}
				}, i * 200);
			}
		},
		plottedMuseums : [] // to hold an array of those museums that have already been plotted
	});
